﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Collections;
using COMOSOFT.OrderBusiness.DataSet.DataSetOrderManagementTableAdapters;
using DevExpress.Spreadsheet;
using COMOSOFT.Class;

namespace COMOSOFT.OrderBusiness.Forms
{
    public partial class FrmSizeBreakdown : Form
    {        
        public FrmSizeBreakdown()
        {
            InitializeComponent();            
        }
        ClassShare cls = new ClassShare("FrmSizeBreakdown");
        int c = 0, r = 0;
        public ArrayList OIDs = new ArrayList();
        public struct NodeSizeBreakdown
        {
            public int SBID;
            public string nsize;
            public string ngroupsize;
            public decimal? nQty;
        }
        List<NodeSizeBreakdown> Listsize=new List<NodeSizeBreakdown>();
        Dictionary<int, String> _Groupsize = new Dictionary<int, string>();
        Dictionary<int, String> _Size = new Dictionary<int, string>();
        ArrayList ArrGroupSize = new ArrayList();
        ArrayList ArrSize = new ArrayList();
        ArrayList ARRSBID = new ArrayList();
        int[,] Matrix = null;
        DataTable dtb;

        DataSet.DataSetOrderManagement dtset = new DataSet.DataSetOrderManagement();
        sp_OrderSizeBreakdownTableAdapter spOrderSBDTableAdapter = new sp_OrderSizeBreakdownTableAdapter();

        #region [InterfaceSpread]
        private void InterfaceSpread()
        {
            //Header
            spreadsheet_SizeBreakdown.ActiveWorksheet.Rows[0][0].SetValue("StyleNo");
            spreadsheet_SizeBreakdown.ActiveWorksheet.Rows[0][1].SetValue("PO");
            spreadsheet_SizeBreakdown.ActiveWorksheet.Rows[0][2].SetValue("Material");
            spreadsheet_SizeBreakdown.ActiveWorksheet.Rows[0][3].SetValue("Inseam/Size");
            //Cot InSeam
           // spreadsheet_SizeBreakdown.ActiveWorksheet.Range["C1:C"+(r+1)].FillColor = Color.WhiteSmoke;
            spreadsheet_SizeBreakdown.ActiveWorksheet.Columns["D"].Font.Color = Color.DarkRed;
            spreadsheet_SizeBreakdown.ActiveWorksheet.Columns["D"].Alignment.Horizontal = SpreadsheetHorizontalAlignment.Center;
            spreadsheet_SizeBreakdown.ActiveWorksheet.Columns["D"].Alignment.Vertical = SpreadsheetVerticalAlignment.Center;
            spreadsheet_SizeBreakdown.ActiveWorksheet.Columns["D"].Font.Bold = true;
            //Cot Size
            spreadsheet_SizeBreakdown.ActiveWorksheet.Rows[0].Font.Color = Color.DarkRed;
            spreadsheet_SizeBreakdown.ActiveWorksheet.Range["A1:D1"].Font.Color = Color.Blue;
            spreadsheet_SizeBreakdown.ActiveWorksheet.Range["A1:D1"].FillColor = Color.WhiteSmoke;
            spreadsheet_SizeBreakdown.ActiveWorksheet.Rows[0].Font.Bold = true;
            spreadsheet_SizeBreakdown.ActiveWorksheet.Rows[0].Alignment.Horizontal = SpreadsheetHorizontalAlignment.Center;
            spreadsheet_SizeBreakdown.ActiveWorksheet.Rows[0].Alignment.Vertical = SpreadsheetVerticalAlignment.Center;

            //spreadsheet_SizeBreakdown.ActiveWorksheet.Range["A0:C1"].Borders.SetAllBorders(Color.Black, BorderLineStyle.Thin);
            spreadsheet_SizeBreakdown.ActiveWorksheet.Range["A2:A"+(r+1)].Merge();
            spreadsheet_SizeBreakdown.ActiveWorksheet.Range["B2:B"+(r+1)].Merge();
            spreadsheet_SizeBreakdown.ActiveWorksheet.Range["C2:C" + (r + 1)].Merge();
            spreadsheet_SizeBreakdown.ActiveWorksheet.SelectedCell = spreadsheet_SizeBreakdown.ActiveWorksheet.Rows[5]["I"];
            spreadsheet_SizeBreakdown.ActiveWorksheet.Name = "SizeBreakDown";         
            for (int i = 0; i < r+1; i++)
            {
                for (int j = 0; j < c+1; j++)
                {
                    spreadsheet_SizeBreakdown.ActiveWorksheet.Rows[i].Height = 100;
                    spreadsheet_SizeBreakdown.ActiveWorksheet.Columns[j].Width = 300;
                    spreadsheet_SizeBreakdown.ActiveWorksheet.Rows[i][j].Alignment.Horizontal = SpreadsheetHorizontalAlignment.Center;
                    spreadsheet_SizeBreakdown.ActiveWorksheet.Rows[i][j].Alignment.Vertical = SpreadsheetVerticalAlignment.Center;     
                    spreadsheet_SizeBreakdown.ActiveWorksheet.Rows[i][j].Font.Bold = true;                    
                }
            }
            spreadsheet_SizeBreakdown.ActiveWorksheet.Rows[0][2].ColumnWidth = 500;
        }
        #endregion

        #region [Load Data]
        public void LoadData()
        {
            try
            {                
                if (OIDs.Count == 1)
                {
                    ARRSBID.Clear();
                    dtb = spOrderSBDTableAdapter.GetData(long.Parse(OIDs[0].ToString()));
                    ArrGroupSize = new ArrayList();
                    ArrSize = new ArrayList();
                    Dictionary<String, int> groupsize = new Dictionary<String, int>();
                    Dictionary<String, int> size = new Dictionary<String, int>();                    
                    foreach (DataRow rowsize in dtb.Rows)
                    {
                        if (ArrGroupSize.Contains(rowsize["InSeam"]) == false)
                        {
                            ArrGroupSize.Add(rowsize["InSeam"]);
                        }
                        if (ArrSize.Contains(rowsize["Size"]) == false)
                        {
                            ArrSize.Add(rowsize["Size"]);
                        }
                        ARRSBID.Add(rowsize["SBID"]);
                    }
                    for (int i = 0; i < 3; i++)
                    {
                        spreadsheet_SizeBreakdown.ActiveWorksheet.Rows[1][i].SetValue(dtb.Rows[0][i + 1]);
                    }
                    //ArrGroupSize.Sort();
                    //ArrSize.Sort();
                    for (int col = 0; col < ArrSize.Count; col++)
                    {
                        spreadsheet_SizeBreakdown.ActiveWorksheet.Rows[0][col + 4].SetValue(ArrSize[col]);
                        size.Add(ArrSize[col].ToString(), col);
                    }
                    for (int row = 0; row < ArrGroupSize.Count; row++)
                    {
                        spreadsheet_SizeBreakdown.ActiveWorksheet.Cells[row + 1, 3].SetValue(ArrGroupSize[row]);
                        groupsize.Add(ArrGroupSize[row].ToString(), row);
                    }
                    foreach (DataRow rowsize in dtb.Rows)
                    {
                        int i = 0;
                        int j = 0;
                        groupsize.TryGetValue(rowsize["InSeam"].ToString(), out i);
                        size.TryGetValue(rowsize["Size"].ToString(), out j);
                        spreadsheet_SizeBreakdown.ActiveWorksheet.Cells[i + 1, j + 4].SetValue(rowsize["Qty"]);                       
                        this.r = i + 1;
                        this.c = j + 4;
                    }
                    string test = spreadsheet_SizeBreakdown.ActiveWorksheet.Cells[1, 6].ToString();
                    //danh dau o co gia tri
                    int colindex = ArrSize.Count;
                    int rowindex = ArrGroupSize.Count;
                    Matrix = new int[20,20];
                    for (int i = 0; i < rowindex; i++)
                    {
                        for (int j = 0; j < colindex; j++)
                        {
                            if (spreadsheet_SizeBreakdown.ActiveWorksheet.Cells[i + 1, j + 4].Value != null && spreadsheet_SizeBreakdown.ActiveWorksheet.Cells[i + 1, j + 4].Value.IsEmpty == false)
                                Matrix[i, j] = 1;
                            else
                                Matrix[i, j] = -1;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                MessageBox.Show("Please check again", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        #endregion

        #region [Get Value]
        public void GetValue()
        {
            try
            {
                _Groupsize.Clear();
                _Size.Clear();
                Listsize.Clear();
                //spreadsheet_SizeBreakdown.Update();
                //danh sach cac size
                for (int col = 0; spreadsheet_SizeBreakdown.ActiveWorksheet.Cells[0, col + 4].Value != null && !spreadsheet_SizeBreakdown.ActiveWorksheet.Cells[0, col + 4].Value.IsEmpty; col++)
                {
                    _Size.Add(col, spreadsheet_SizeBreakdown.ActiveWorksheet.Cells[0, col +4].Value.ToString());
                }
                //danh sach cac groupsize
                for (int row = 0; spreadsheet_SizeBreakdown.ActiveWorksheet.Cells[row + 1, 3].Value != null && !spreadsheet_SizeBreakdown.ActiveWorksheet.Cells[row + 1, 3].Value.IsEmpty; row++)
                {
                    _Groupsize.Add(row, spreadsheet_SizeBreakdown.ActiveWorksheet.Cells[row + 1, 3].Value.ToString());
                }
                //tao sizebreakdown
                int[] rowindex = _Groupsize.Keys.ToArray();
                int[] colindex = _Size.Keys.ToArray();
                int sbid = 0;
                for (int i = 0; i <rowindex .Length; i++)
                {
                    for (int j = 0; j < colindex.Length; j++)
                    {
                        if (spreadsheet_SizeBreakdown.ActiveWorksheet.Cells[i + 1, j + 4].Value != null && !spreadsheet_SizeBreakdown.ActiveWorksheet.Cells[i + 1, j + 4].Value.IsEmpty)
                        {
                            if (spreadsheet_SizeBreakdown.ActiveWorksheet.Cells[i + 1, j + 4].Value.IsNumeric)
                            {
                                NodeSizeBreakdown newNode = new NodeSizeBreakdown();
                                //string _SBID = ARRSBID[sbid].ToString();
                                if (sbid < ARRSBID.Count && Matrix[i, j] == 1)
                                    newNode.SBID = Convert.ToInt16(ARRSBID[sbid]);
                                else
                                {
                                    newNode.SBID = -1;
                                    sbid--;
                                }
                                //_Groupsize.TryGetValue(rowindex[i], out newNode.ngroupsize);
                                //_Size.TryGetValue(colindex[j], out newNode.nsize);
                                newNode.ngroupsize = spreadsheet_SizeBreakdown.ActiveWorksheet.Cells[i + 1, 3].Value.ToString();
                                newNode.nsize = spreadsheet_SizeBreakdown.ActiveWorksheet.Cells[0, j + 4].Value.ToString();
                                newNode.nQty = Convert.ToDecimal(spreadsheet_SizeBreakdown.ActiveWorksheet.Cells[i+1, j + 4].Value.ToString());
                                Listsize.Add(newNode);
                                sbid++;
                            }
                            else
                            {
                                MessageBox.Show("Quantity must be an number. Please check again.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                _Groupsize.Clear();
                                _Size.Clear();
                                Listsize.Clear();
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                MessageBox.Show("Please check again", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        #endregion

        private void FrmSizeBreakdown_Load(object sender, EventArgs e)
        {
            LoadData();
            InterfaceSpread();            
        }

        #region [EvenButton]
        private void dataNavigator1_ButtonClick(object sender, DevExpress.XtraEditors.NavigatorButtonClickEventArgs e)
        {
            switch (e.Button.Tag.ToString())
            {
                case "Save":
                    try
                    {
                        GetValue();
                        int OID = Convert.ToInt16(OIDs[0]);
                        foreach (NodeSizeBreakdown nodesize in Listsize)
                        {
                            if (nodesize.SBID == -1)
                            {
                                string remarks = "";
                                cls.UpdateData("sp_OrderSizeBreakdownInsert", new string[5] { "@oid", "@size", "@inseam", "@qty", "@remarks" }, new object[5] { OID, nodesize.nsize, nodesize.ngroupsize, nodesize.nQty, remarks });
                            }
                            else
                            {
                                cls.UpdateData("sp_OrderSizeBreakdownUpdate", new string[4] { "@sbid", "@size", "@inseam", "@qty" }, new object[4] { nodesize.SBID, nodesize.nsize, nodesize.ngroupsize, nodesize.nQty });
                            }
                        }
                        FrmSizeBreakdown_Load(sender, e);
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                        MessageBox.Show("Please check again", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    break;
                case "Delete":
                    break;
                case "Refresh":
                    FrmSizeBreakdown_Load(sender, e);
                    break;
                case "Export":
                    String fileName = null;
                    SaveFileDialog sfd = new SaveFileDialog();
                    sfd.Filter = "Excel 2003|*.xls|Excel 2007|*.xlsx";
                    sfd.Title = "Save an Excel File";
                    sfd.FileName = "SizeBreakDown_" + dtb.Rows[0][0].ToString() + String.Format("{0:MMMddyyyy}", DateTime.Now);
                    if (sfd.ShowDialog() == DialogResult.OK)
                    {
                        try
                        {
                            fileName = sfd.FileName;
                            spreadsheet_SizeBreakdown.SaveDocument(fileName, DocumentFormat.Xls);
                            DialogResult dlr = MessageBox.Show("Open File Export", "Do you want to open it?",
                                               MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                            if (dlr == DialogResult.Yes)
                            {
                                System.Diagnostics.Process.Start(fileName);
                            }
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(ex.Message);
                        }
                    }
                    break;
                default :
                    break;
            }
        }
        #endregion
    }
}
